#include "include_gl.h"
#include "App.h"
#include "InputHandler.h"

#include <iostream>

static void error_callback(int error, const char* description)
{
	fputs(description, stderr);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
	if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
		glfwSetWindowShouldClose(window, GL_TRUE);
}

int main(int argc, char** argv)
{
	GLFWwindow* window;
	glfwSetErrorCallback(error_callback);
	if (!glfwInit())
		exit(EXIT_FAILURE);

	window = glfwCreateWindow(640, 480, "FEM Fluid", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		exit(EXIT_FAILURE);
	}
	glfwMakeContextCurrent(window);

	int err = flextInit(window);
	if(!err)
	{
		fputs("Error loading functions!\n", stderr);
		glfwDestroyWindow(window);
		glfwTerminate();
		exit(EXIT_FAILURE);
	}


	//glfwSetKeyCallback(window, key_callback);
	//glfwSetWindowSizeCallback(window, window_size_callback);
	//glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

	float ratio;
	int width, height;
	glfwGetFramebufferSize(window, &width, &height);
	ratio = width / (float) height;
	glViewport(0, 0, width, height);
	glClear(GL_COLOR_BUFFER_BIT);

	InputHandler* inputHandler = new InputHandler(window);

	App* app = new App();
	if (!app->init(window, inputHandler))
		fputs("Error during init\n", stderr);

	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
		printf("GL Error during init!");

	glfwSwapInterval(0);

	while (!glfwWindowShouldClose(window))
	{
		inputHandler->update();
		if (!app->loop())
			fputs("Error during loop\n",stderr);

		GLenum error = glGetError();
		if (error != GL_NO_ERROR)
			printf("GL Error during loop!");
		
		glfwSwapBuffers(window);
		glfwPollEvents();
	}

	delete app;
	glfwDestroyWindow(window);
	glfwTerminate();
	exit(EXIT_SUCCESS);
}